package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private ApArticleService apArticleService;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;


    /**
     * 上传静态文件到minio
     */
    @Async
    @Override
    public void buildArticleToMinio(ApArticle apArticle, String content) throws Exception {

        if (StringUtils.isNotBlank(content)){

            Template template = configuration.getTemplate("article.ftl");

            Map<String ,Object> contentDataModel = new HashMap<>();
            contentDataModel.put("content", JSON.parseArray(content));


            StringWriter out = new StringWriter();

            template.process(contentDataModel,out);

            InputStream in = new ByteArrayInputStream(out.toString().getBytes());

            String path = fileStorageService.uploadHtmlFile("", apArticle.getId()+".html", in);

            System.out.println(path);

            apArticleService.update(Wrappers.<ApArticle>lambdaUpdate().eq(ApArticle::getId,apArticle.getId())
                    .set(ApArticle::getStaticUrl,path));


        }
    }


}
